package dht.storage;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;

import dht.IStorage;
import dht.entity.DataObject;
import dht.entity.GlobalVariables;
import dht.throwable.DhtException;

public class FakeStorageImpl implements IStorage {

	public FakeDirectory directory;

	public FakeStorageImpl() {
		directory = new FakeDirectory();
		directory.initialize();
	}

	@Override
	public DataObject read(String fileName) throws DhtException {
		DataObject dataObject = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(genFileName(fileName));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new DhtException(e.getMessage());
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[GlobalVariables.readBufferSize];
		int len;
		try {
			while ((len = fis.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new DhtException(e.getMessage());
		}
		try {
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new DhtException(e.getMessage());
		}
		dataObject = new DataObject();
		dataObject.setBlockName(fileName);
		dataObject.setData(baos.toByteArray());
		return dataObject;
	}

	@Override
	public void write(DataObject dataObject, boolean overwrite)
			throws DhtException {
		int offset = 0;
		int size = 0;
		byte[] data = dataObject.getData();
		if (data != null) {
			size = data.length;
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream("/dev/null");
			while (offset < size) {
				int len = Math.min(GlobalVariables.writeBufferSize, size
						- offset);
				fos.write(data, offset, len);
				offset += len;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new DhtException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			throw new DhtException(e.getMessage());
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new DhtException(e.getMessage());
			}
		}
	}

	private String genFileName(String fileName) {
		return GlobalVariables.dataPath + "/fake_file_1";
	}

	@Override
	public Vector<String> getFileNamesByVnodeIds(Vector<Integer> vnodeIds)
			throws DhtException {
		Vector<String> fileNames = new Vector<String>();
		for (Integer vnodeId : vnodeIds) {
			fileNames.addAll(directory.getFileNamesByVnodeId(vnodeId));
		}
		return fileNames;
	}

	@Override
	public void remove(String fileName) throws DhtException {
		// TODO Auto-generated method stub

	}
}
